import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/cupertino.dart';

import 'package:netease_music_api/netease_music_api.dart';

import '/component.dart';
import '/repository/netease.dart';

class BackgroundInterceptors {
  // 获取播放地址
  static Future<String> playUriInterceptor(
      String? mediaId, String? fallbackUri) async {
    final result = await NeteaseMusicApi().songUrl([mediaId!]);
    if (result.codeEnum != RetCode.Ok) {
      return fallbackUri ?? '';
    }

    /// some devices do not support http request.
    return result.data!.first.url!.replaceFirst("http:/", "https:/");
  }

  static Future<Uint8List> loadImageInterceptor(MediaDetails metadata) async {
    final ImageStream stream =
        CachedImage(metadata.artUri.toString()).resolve(ImageConfiguration(
      size: const Size(150, 150),
      devicePixelRatio: WidgetsBinding.instance.window.devicePixelRatio,
    ));
    final image = Completer<ImageInfo>();
    stream.addListener(ImageStreamListener((info, a) {
      image.complete(info);
    }, onError: (exception, stackTrace) {
      image.completeError(exception, stackTrace);
    }));
    final result = await image.future
        .then((image) => image.image.toByteData(format: ImageByteFormat.png))
        .then((byte) => byte!.buffer.asUint8List())
        .timeout(const Duration(seconds: 10));
    debugPrint("load image for : ${metadata.title} ${result.length}");
    return result;
  }
}
